package com.best.oasis.settlement.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

import com.best.oasis.settlement.common.configmapping.EntityCodePrefixMapping;
import com.best.oasis.settlement.common.configmapping.EntityCodePrefixMapping.CodeConfig;

/**
 * 根据ID，生成各Entity的code
 * 
 * @author bl00252
 *
 */
public class CodeUtil {
	
	public static String generateCode(Class<?> entityClass,Long id){
//		Assert.notNull(entityClass);
		String className = getClassName( entityClass );
		
		CodeConfig config =  EntityCodePrefixMapping.MAP.get(className);
		
		if(config==null){
			config = EntityCodePrefixMapping.DEFAULT_CONFIG;
		}
		return generateCode(config.getPrefix(),config.getDateFormat(),config.getNumberLength(),id);
	}
	
	private static String generateCode(String prefix,String dataFormat,int numberLength, Long id){
		
		if(StringUtils.isBlank(dataFormat)){
			return prefix + String.format("%0"+numberLength+"d", id);
		}else{
			DateFormat df = null;
			try{
				df = new SimpleDateFormat(dataFormat);
			}catch (Exception e){
				df = new SimpleDateFormat(EntityCodePrefixMapping.DEFAULT_CONFIG.getDateFormat());
			}
			return prefix + df.format(new Date()) + String.format("%0"+numberLength+"d", id);	
		}
	}
    public static String getClassName( Class<?> entityClass ) 
    {
        String className = entityClass.getName();
        //System.out.println("clazzName: " + clazzName );
        if( className.indexOf('$') > 0 ){
        	className = className.substring(0, className.lastIndexOf('$'));
        }
        if( className.indexOf('.') > 0 ){
        	className = className.substring(className.lastIndexOf('.') + 1,className.length());
        }
        //System.out.println("clazzName: " + clazzName );
        return className;
    }
    public static void main(String[] args){
        for(long i=0; i<10; i++){
            System.out.println(CodeUtil.generateCode("AR","yyyyMMdd",8,i));
        }
        for(long i=0; i<20; i++){
            System.out.println(CodeUtil.generateCode("",null,1,i));
        }
        
    }
}
